package com.ecourseapp.NativeForRN;


import android.app.Activity;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.Toast;

import com.ecourseapp.ActivityPool.ActivityPageOne;
import com.ecourseapp.ActivityPool.LoginResponse;
import com.ecourseapp.util.ECourseConstant;
import com.ecourseapp.util.RNCommonResult;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.uimanager.IllegalViewOperationException;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 原生Activity与React交互——模块
 */

public class BaseBridgeModule extends ReactContextBaseJavaModule {

    public BaseBridgeModule(ReactApplicationContext reactContext) {
        super(reactContext);

        //给上下文对象赋值
        Test.myContext=reactContext;

    }

    @Override
    public String getName() {
        return "BaseBridge";
    }
    //注意：记住getName方法中的命名名称，JS中调用需要


    @ReactMethod
    public void globalSingleton(final String key, final Promise promise) {

        Map<String, Object> map = new HashMap<>();

        map.put("userInfo", ECourseConstant.userInfo);
        map.put("map", ECourseConstant.map);
        map.put("eCourseFirstRouter", ECourseConstant.eCourseFirstRouter);

        promise.resolve(new Gson().toJson(map));
    }

    @ReactMethod
    public void setGlobalSingletonMap(final String key, final String value, final Promise promise) {
        try {
            ECourseConstant.map.put(key, value);
            promise.resolve(new Gson().toJson(new RNCommonResult()));
        } catch (Exception e) {
            RNCommonResult result = new RNCommonResult();
            result.msg = e.toString();
            result.success = false;
            promise.resolve(new Gson().toJson(result));
        }
    }

    @ReactMethod
    public void globalSingletonWithSCallBack(Callback successBack, Callback errorBack) {
        try {
            Map<String, Object> map = new HashMap<>();

            map.put("userInfo", ECourseConstant.userInfo);
            map.put("map", ECourseConstant.map);
            map.put("eCourseFirstRouter", ECourseConstant.eCourseFirstRouter);
            successBack.invoke(new Gson().toJson(map));
        } catch (Exception e) {
            errorBack.invoke(e.getMessage());
        }
    }

    @ReactMethod
    public void show(String msg) {
        Toast.makeText(getReactApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

    // 获取应用包名
    // 要导出一个方法给JavaScript使用，Java方法需要使用注解@ReactMethod
    @ReactMethod
    public void showPackageName() {
        String name = getReactApplicationContext().getPackageName();
        Toast.makeText(getReactApplicationContext(), name, Toast.LENGTH_LONG).show();
    }

    //注意：startActivityFromJS、dataToJS方法添加RN注解(@ReactMethod)，否则该方法将不被添加到RN中

    @ReactMethod
    public void startActivityFromJS(String name, String params) {
        try {
            Activity currentActivity = getCurrentActivity();
            if (null != currentActivity) {
                Class toActivity = Class.forName(name);
                Intent intent = new Intent(currentActivity, toActivity);
                intent.putExtra("params", params);
                currentActivity.startActivity(intent);
            }
        } catch (Exception e) {
            throw new JSApplicationIllegalArgumentException(
                    "不能打开Activity : " + e.getMessage());
        }
    }

    @ReactMethod
    public void dataToJS(Callback successBack, Callback errorBack) {
        try {
            Activity currentActivity = getCurrentActivity();
            String result = currentActivity.getIntent().getStringExtra("data");
            if (TextUtils.isEmpty(result)) {
                result = "没有数据";
            }
            successBack.invoke(result);
        } catch (Exception e) {
            errorBack.invoke(e.getMessage());
        }
    }


    @ReactMethod
    public void getData(
            int one,
            int two,
            Callback errorCallback,
            Callback successCallback) {
        try {
            successCallback.invoke("12345");
        } catch (IllegalViewOperationException e) {
            errorCallback.invoke(e.getMessage());
        }
    }

    @ReactMethod
    public void backToExue() {
        Activity currentActivity = getCurrentActivity();
        if (currentActivity != null) {
            currentActivity.finish();
        }
    }

    @ReactMethod
    public void playVideo(String url) {
        try {
            VideoPlayerWithControllerActivity.naveToActivity(getCurrentActivity(), url);
        } catch (Exception e) {
            throw new JSApplicationIllegalArgumentException(
                    "打开视频失败 : " + e.getMessage());
        }
    }

    @ReactMethod
    public void login(final Promise promise) {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        Request request = new Request.Builder()
                // .url("http://it.family.juziwl.cn:8090/family/user/register/login")
                .url("http://test.family.juziwl.cn/family/user/register/login")
                .post(RequestBody.create(mediaType, ActivityPageOne.loginJson))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request)
                .enqueue(new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        promise.reject(e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final LoginResponse loginResponse = new Gson().fromJson(response.body().string(), LoginResponse.class);
                        if (loginResponse.status == 200) {
                            ECourseConstant.userInfo.loginType = loginResponse.content.userType;
                            ECourseConstant.userInfo.uuid = loginResponse.content.userId;
                            ECourseConstant.userInfo.token = loginResponse.content.token;
                            ECourseConstant.userInfo.imId = loginResponse.content.imId;
                            if (promise != null) {
                                promise.resolve(loginResponse.content.token);
                            }
                        } else {
                            promise.reject(loginResponse.errorMsg);
                        }
                    }
                });
    }


    @ReactMethod
    public void setPayPassword() {
        //调用Test类中的原生方法。
        new Test().fun();
    }

}
